<?php

namespace app\payment\admin;

use app\common\builder\ZBuilder;
use app\payment\model\PaymentCash as PaymentCashModel;
use app\payment\model\Mconfig as MconfigModel;

/**
 * 商户钱包控制器
 */
class Cash extends Index
{

    protected function initialize()
    {
        parent::initialize();
        if (!in_array(request()->action(), ['index'])) {
            if ($this->no_auth) {
                $this->error('权限不足！');
            }
        }

        if (in_array(request()->action(), ['edit'])) {
            $this->error('NO');
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 设置搜索参数
        $search = ['merchant_id' => '商户号'];

        // 获取查询条件
        $map = $this->getMap();

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
            $search = [];
        }
        /*
          if ($this->is_agent) {
          $sub_merchant = get_sub_merchant($this->merchant_id);
          if ($sub_merchant) {
          $sub_merchant[] = $this->merchant_id;
          $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
          if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
          $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
          }
          }
          }
         */

        $list_rows = input('list_rows', 20) >= 20 ? 20 : input('list_rows');
        // 数据列表
        $data_list = PaymentCashModel::where($map)->order('create_time desc')->paginate($list_rows);
        // 分页数据
        $page = $data_list->render();

        $items = [
            ['merchant_id', '商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['sum_cash', '总金额', 'callback', function ($value) {
                return $value / 100;
            }],
            ['cash', '剩余余额', 'callback', function ($value) {
                return $value / 100;
            }],
            ['count', '来源次数'],
            ['freeze_cash', '冻结金额', 'callback', function ($value) {
                return $value / 100;
            }],
            ['transit_cash', '过渡金额', 'callback', function ($value) {
                return $value / 100;
            }],
            ['refund_sum_cash', '退款总金额', 'callback', function ($value) {
                return $value / 100;
            }],
            ['refund_count', '退款总次数'],
            ['withdrawal_sum_cash', '提现总金额', 'callback', function ($value) {
                return $value / 100;
            }],
            ['withdrawal_count', '提现总次数'],
            ['paid_sum_cash', '代付总金额', 'callback', function ($value) {
                return $value / 100;
            }],
            ['paid_cash', '代付余额', 'callback', function ($value) {
                return $value / 100;
            }],
            ['paid_count', '代付总次数'],
            ['dates', '来源日期', 'callback', function ($value) {
                return date('Y-m-d', strtotime($value));
            }],
            ['create_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['status', '状态', 'status'],
            ['right_button', '操作', 'btn']
        ];

        $hideCheckbox = false;
        if ($this->no_auth) {
            unset($items[0]);
            unset($items[16]);
            $hideCheckbox = true;
        }

        /*
          if ($this->is_agent) {
          // 显示搜索项
          $search = ['merchant_id' => '商户号'];
          // 显示列
          array_unshift($items, ['merchant_id', '商户', 'callback', function($value) {
          return $value . '<br/>' . get_user_nickname($value);
          }, '', 'text-center']);
          }
         */

        // 全选过渡金额审核
        $all_audit = [
            'title' => '全选过渡金额审核',
            'icon' => 'fa fa-fw fa-vimeo',
            'class' => 'btn btn-danger ajax-get confirm',
            'href' => url('allAudit'),
            'data-title' => '全选过渡金额审核',
            'data-tips' => '请先看每个商户号对应的过渡金额有没有问题'
        ];

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->hideCheckbox($hideCheckbox)
            ->setPageTitle('钱包管理(元)') // 设置页面标题
            ->setTableName('payment_cash') // 设置数据表名
            ->setPrimaryKey('merchant_id') // 设置主键名为id
            ->setSearch($search) // 设置搜索参数
            ->addColumns($items)
            ->addTopButtons('') // 批量添加顶部按钮
            ->addTopButton('all_audit', $all_audit) // 添加按钮
            ->addRightButtons('edit') // 批量添加右侧按钮
            ->addRightButton('audit', ['title' => '过渡金额审核', 'class' => 'ajax-get confirm', 'icon' => 'fa fa-fw fa-check-circle', 'href' => url('audit', ['id' => '__id__'])])
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染页面
    }

    /**
     * 修改
     * @param null $id 
     * @return mixed
     */
    public function edit($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        if ($this->role > 1) {
            $this->error('只允许超级管理员执行此操作！');
        }

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            $user = MconfigModel::where(['id' => $data['merchant_id']])->find();
            if ($user['settlement_type'] == 1 && $user['settlement_day'] == 0) {
                $this->error('商户结算类型是D0,不能手动更新，请直接执行数据库语句！');
            }

            if ($temp = PaymentCashModel::update($data)) {
                // 记录行为
                action_log('payment_cash_edit', 'cash', $temp['merchant_id'], UID, json_encode($temp));
                $this->success('编辑成功', url('index'));
            } else {
                $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = PaymentCashModel::where('merchant_id', $id)->field(true)->find();
        if (!$info) {
            $this->error('参数有误！');
        }

        $items = [
            ['hidden', 'merchant_id', $id],
            ['static', 'merchant_id', '商户号', '商户名称：' . get_user_nickname($info['merchant_id']), '', '', ''],
            ['text', 'cash', '商户现金余额（单位：分）'],
            ['text', 'sum_cash', '商户总现金（单位：分）'],
            ['text', 'freeze_cash', '冻结金额（单位：分）'],
            ['text', 'transit_cash', '过渡金额（单位：分）'],
            ['text', 'count', '来源总次数'],
            ['text', 'withdrawal_sum_cash', '商户提现总金额（单位：分）'],
            ['text', 'withdrawal_count', '提现总次数'],
            ['text', 'paid_sum_cash', '商户代付总金额（单位：分）'],
            ['text', 'paid_cash', '商户代付余额（单位：分）'],
            ['text', 'paid_count', '代付总次数'],
            ['text', 'dates', '上次统计时间'],
            ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['radio', 'status', '状态', '', ['禁用', '启用']],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems($items)
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 过渡金额审核通过
     * @param null $id 
     * @return mixed
     */
    public function audit($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }
        // 获取数据
        $info = PaymentCashModel::where('merchant_id', $id)->field(true)->find();
        if (!$info || $info['status'] != 1 || $info['transit_cash'] == 0) {
            $this->error('参数有误！');
        }

        try {
            PaymentCashModel::where('merchant_id', $id)
                ->inc('cash', $info['transit_cash'])
                ->inc('sum_cash', $info['transit_cash'])
                ->update(['transit_cash' => 0, 'update_time' => time()]);
        } catch (\Exception $e) {
            payment_error_log(810000, $info, $e->getMessage());
            $this->error("失败，请联系程序员处理：{$e->getMessage()}");
        }
        $this->success("操作成功");
    }

    /**
     * 全选过渡金额审核通过
     * @return mixed
     */
    public function allAudit()
    {
        // 获取数据
        $info = PaymentCashModel::where(['status' => 1])
            ->where('transit_cash', '<>', 0)
            ->select();

        try {
            foreach ($info as $key => $value) {
                PaymentCashModel::where('merchant_id', $value['merchant_id'])
                    ->inc('cash', $value['transit_cash'])
                    ->inc('sum_cash', $value['transit_cash'])
                    ->update(['transit_cash' => 0, 'update_time' => time()]);
            }
        } catch (\Exception $e) {
            payment_error_log(810001, $info, $e->getMessage());
            $this->error("失败，请联系程序员处理：{$e->getMessage()}");
        }
        $count = count($info);
        $this->success("操作成功，共操作｛{$count}｝个商户号！");
    }
}
